package com.example.choupaiapp.main.activity.find;

import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.view.ViewPager;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.method.MovementMethod;
import android.text.style.DynamicDrawableSpan;
import android.text.style.StyleSpan;
import android.view.View;
import android.view.ViewParent;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.dueeeke.videoplayer.player.VideoView;
import com.dueeeke.videoplayer.player.VideoViewManager;
import com.example.choupaiapp.R;
import com.example.choupaiapp.common.adapter.BaseAdapterHelper;
import com.example.choupaiapp.common.adapter.QuickAdapter;
import com.example.choupaiapp.common.constant.Contacts;
import com.example.choupaiapp.common.finalokgo.callback.Callback;
import com.example.choupaiapp.common.finalokgo.request.RequestType;
import com.example.choupaiapp.common.ui.activity.CommonActivity;
import com.example.choupaiapp.common.util.ContextUtil;
import com.example.choupaiapp.common.util.DateFormatUtil;
import com.example.choupaiapp.common.util.DialogUtil;
import com.example.choupaiapp.common.util.GsonUtil;
import com.example.choupaiapp.common.util.SharedPreferencesHelp;
import com.example.choupaiapp.common.util.Utils;
import com.example.choupaiapp.common.view.XListView;
import com.example.choupaiapp.main.activity.home.CommentDetailActivity;
import com.example.choupaiapp.main.activity.home.OtherInfoActivity;
import com.example.choupaiapp.main.adapter.VerticalViewPagerAdapter;
import com.example.choupaiapp.main.bean.CommentListBean;
import com.example.choupaiapp.main.bean.CommentRemindJsonBean;
import com.example.choupaiapp.main.bean.FindDetailBean;
import com.example.choupaiapp.main.bean.FindListBean;
import com.example.choupaiapp.main.bean.RemindJson;
import com.example.choupaiapp.main.bean.SendCodeBean;
import com.example.choupaiapp.main.bean.ShareDataBean;
import com.example.choupaiapp.main.bean.ShareFindBean;
import com.example.choupaiapp.main.bean.UserInfoBean;
import com.example.choupaiapp.main.bean.VideoListBean;
import com.example.choupaiapp.main.callback.VideoClickListener;
import com.example.choupaiapp.main.callback.WechatCallBack;
import com.example.choupaiapp.main.constant.Config;
import com.example.choupaiapp.main.constant.Url;
import com.example.choupaiapp.main.util.DetailCommentDialog;
import com.example.choupaiapp.main.util.DialogFragmentDataCallback;
import com.example.choupaiapp.main.util.WXShareUtil;
import com.example.choupaiapp.main.util.WechatLoginUtil;
import com.example.choupaiapp.main.util.ffmpeg.FFmpegHandler;
import com.example.choupaiapp.main.util.ffmpeg.FFmpegUtil;
import com.example.choupaiapp.main.util.jpush.ExampleUtil;
import com.example.choupaiapp.main.util.video.PreloadManager;
import com.example.choupaiapp.main.util.video.VideoDetailHashMap;
import com.example.choupaiapp.main.util.video.VideoHashMap;
import com.example.choupaiapp.main.util.video.VideoMineHashMap;
import com.example.choupaiapp.main.util.video.VideoPraiseHashMap;
import com.example.choupaiapp.main.view.video.VerticalViewPager;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.GetRequest;
import com.lzy.okserver.OkDownload;
import com.lzy.okserver.download.DownloadListener;
import com.lzy.okserver.download.DownloadTask;
import com.orhanobut.logger.Logger;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.shuyu.textutillib.RichTextView;
import com.shuyu.textutillib.SmileUtils;
import com.shuyu.textutillib.TextCommonUtils;
import com.shuyu.textutillib.listener.ITextViewShow;
import com.shuyu.textutillib.listener.SpanAtUserCallBack;
import com.shuyu.textutillib.listener.SpanTopicCallBack;
import com.shuyu.textutillib.listener.SpanUrlCallBack;
import com.shuyu.textutillib.model.TopicModel;
import com.shuyu.textutillib.model.UserModel;
import com.shuyu.textutillib.span.ClickAtUserSpan;
import com.shuyu.textutillib.span.ClickTopicSpan;
import com.shuyu.textutillib.span.LinkSpan;
import com.sina.weibo.sdk.WbSdk;
import com.sina.weibo.sdk.api.TextObject;
import com.sina.weibo.sdk.api.WeiboMultiMessage;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.share.WbShareCallback;
import com.sina.weibo.sdk.share.WbShareHandler;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzonePublish;
import com.tencent.connect.share.QzoneShare;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.ypx.imagepicker.utils.PBitmapUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import cn.jpush.android.api.JPushInterface;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by ASUS on 2019/11/11.
 */

public class FindVideoDetailActivity extends CommonActivity implements VideoClickListener, OnRefreshLoadMoreListener, WbShareCallback, WechatCallBack, DialogFragmentDataCallback {

    @BindView(R.id.viewpager)
    VerticalViewPager viewpager;
    private int mCurrentPosition;
    private int mPlayingPosition;
    StyleSpan span = new StyleSpan(Typeface.BOLD);
    StyleSpan span2 = new StyleSpan(Typeface.BOLD);
    StyleSpan span1 = new StyleSpan(Typeface.NORMAL);
    StyleSpan span3 = new StyleSpan(Typeface.NORMAL);
    private Drawable drawable_select;
    private Drawable drawable_unselect;
    private String et_flag = "comment";
    private String replyUserId;
    private String replyCommentId;
    private int pageNum = 1;
    private int pageSize = 10;
    private Tencent mTencent;
    private OkDownload okDownload;
    private List<DownloadTask> values;
    private DownloadTask task;
    String photoMark = "";
    public final static int MSG_BEGIN = 9012;

    public final static int MSG_PROGRESS = 1002;

    public final static int MSG_FINISH = 1112;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_BEGIN:
                    Logger.e("添加水印开始");
                    break;
                case MSG_FINISH:
                    Logger.e("添加水印结束");
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                        ContentValues contentValues = new ContentValues();
                        contentValues.put(MediaStore.Video.Media.DISPLAY_NAME, "water_marker_" + System.currentTimeMillis() + "." + photoMark.substring(photoMark.lastIndexOf(".")));
                        contentValues.put(MediaStore.Video.Media.MIME_TYPE, "video/" + photoMark.substring(photoMark.lastIndexOf(".")));
                        contentValues.put(MediaStore.Video.Media.RELATIVE_PATH, "Movies/choupai_save_video");
                        Uri uri = ContextUtil.getContext().getContentResolver().insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, contentValues);
                        boolean b = PBitmapUtils.copyFile(ContextUtil.getContext(), photoMark, uri);
                        if (b) {
                            showToast("下载完成");
                        }
                    }else{
                        showToast("下载完成");
                    }
                    break;
                case MSG_PROGRESS:
                    Logger.e("添加水印中");
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * VerticalViewPager是否反向滑动
     */
    private boolean mIsReverseScroll;

    private PreloadManager mPreloadManager;
    private VerticalViewPagerAdapter verticalViewPagerAdapter;
    private List<VideoListBean> listBeans;
    private int videoId;
    private UserInfoBean mUserInfoBean;
    private String categoriesId;
    private QuickAdapter<CommentListBean.PageBean.ListBean> quickAdapter;
    private SmartRefreshLayout refreshLayout;
    private String flag;
    private int sharePosition;
    private int dataPosition;
    private WbShareHandler shareHandler;
    private RichTextView comment_et;
    private DetailCommentDialog commentDialogFragment;
    private int commentPosition;
    @BindView(R.id.container_framelayout)
    FrameLayout container_framelayout;
    @BindView(R.id.top_ll)
    LinearLayout top_ll;
    private ImageView empty_img;
    private String replayName = "";
    private String replayContent = "";
    private List<UserModel> nameList;
    private ListView listView;
    private int replyPosition;
    private FFmpegHandler ffmpegHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setAnimate(false);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_detail);
    }

    SpanAtUserCallBack spanAtUserCallBack = new SpanAtUserCallBack() {
        @Override
        public void onClick(View view, UserModel userModel1) {
            Bundle bundle = new Bundle();
            bundle.putString("userId", userModel1.getUser_id());
            bundle.putString("userName", userModel1.getUser_name());
            startActivity(OtherInfoActivity.class, bundle);
            if (view instanceof TextView) {
                ((TextView) view).setHighlightColor(Color.TRANSPARENT);
            }
        }
    };

    /**
     * 处理自己的表情
     */
    private void initEmoji() {
        List<Integer> data = new ArrayList<>();
        List<String> strings = new ArrayList<>();
        int resofficial = getResources().getIdentifier("icon_comment_official", "mipmap", getPackageName());
        int resgod = getResources().getIdentifier("icon_comment_god", "mipmap", getPackageName());
        data.add(resofficial);
        strings.add("[icon_comment_official]");
        data.add(resgod);
        strings.add("[icon_comment_god]");
        /**初始化为自己的**/
        SmileUtils.addPatternAll(SmileUtils.getEmoticons(), strings, data);
    }

    @Override
    protected void initView() {
        container_framelayout.measure(0, 0);

        EventBus.getDefault().register(this);

        initEmoji();

        top_ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Utils.isDoubleClick()) {
                    return;
                }
                if (top_ll.getVisibility() == View.GONE) {
                } else {
                    top_ll.setVisibility(View.GONE);
                    container_framelayout
                            .animate()
                            .translationY(0)
                            .setDuration(200)
                            .start();
                }
            }
        });

        ffmpegHandler = new FFmpegHandler(mHandler);

        drawable_select = getResources().getDrawable(R.mipmap.icon_praise_select);
        drawable_unselect = getResources().getDrawable(R.mipmap.item_praise);

        mPreloadManager = PreloadManager.getInstance(this);

        mUserInfoBean = (UserInfoBean) SharedPreferencesHelp.getBean("userInfo");

        viewpager.setOffscreenPageLimit(4);

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            videoId = bundle.getInt("videoId");
            categoriesId = bundle.getString("categoriesId");
            dataPosition = bundle.getInt("position");
            flag = bundle.getString("flag");
            if ("mineVideo".equals(flag)) {
                VideoView videoView = new VideoView(context);
                VideoDetailHashMap.getIntance().put(videoId, videoView);
            } else if ("mineAll".equals(flag)) {
                VideoDetailHashMap.getIntance().put(videoId, VideoMineHashMap.getIntance().get(videoId));
            } else if ("praise".equals(flag)) {
                VideoDetailHashMap.getIntance().put(videoId, VideoPraiseHashMap.getIntance().get(videoId));
            } else if ("search".equals(flag)) {
                VideoDetailHashMap.getIntance().put(videoId, VideoPraiseHashMap.getIntance().get(videoId));
            } else if ("recommend".equals(flag)) {
                VideoDetailHashMap.getIntance().put(videoId, VideoHashMap.getIntance().get(videoId));
            } else {
                VideoView videoView = new VideoView(context);
                VideoDetailHashMap.getIntance().put(videoId, videoView);
            }
        } else {
            Logger.e("bundlu==null");
        }

        VideoListBean videobean = (VideoListBean) bundle.getSerializable("data");
        listBeans = new ArrayList<>();
        listBeans.add(videobean);

        verticalViewPagerAdapter = new VerticalViewPagerAdapter(listBeans, this);

        viewpager.setAdapter(verticalViewPagerAdapter);

        viewpager.setOverScrollMode(View.OVER_SCROLL_NEVER);

        viewpager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels);
                if (position > mPlayingPosition) {
                    mIsReverseScroll = false;
                } else if (position < mPlayingPosition) {
                    mIsReverseScroll = true;
                }
            }

            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                mCurrentPosition = position;
                if (position == mPlayingPosition) return;
                startPlay(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                super.onPageScrollStateChanged(state);
                if (mCurrentPosition == mPlayingPosition) return;
                if (state == VerticalViewPager.SCROLL_STATE_IDLE) {
                    mPreloadManager.resumePreload(mCurrentPosition, mIsReverseScroll);
                } else {
                    mPreloadManager.pausePreload(mCurrentPosition, mIsReverseScroll);
                }
            }
        });

        viewpager.post(new Runnable() {
            @Override
            public void run() {
                startPlay(0);
            }
        });

    }

    @Override
    protected void initData() {
        requestData();

        showDialog(this, null);
        HttpParams params1 = new HttpParams();
        params1.put("id", videoId);
        if (mUserInfoBean != null) {
            params1.put("userId", mUserInfoBean.getUser().getUserId());
        }
        finalOkGo.request(RequestType.POST, Url.FIND_DETAIL, params1, Url.FIND_DETAIL, new Callback<FindDetailBean>() {
            @Override
            public void onSuccess(FindDetailBean findDetailBean) {
                if (findDetailBean.getCode() == Contacts.SUCCESS) {
                } else {
                    dismissDialog();
                    if (findDetailBean.getCode() == Contacts.TOKEN_EMPTY) {
                    } else {
                        showImageToas(findDetailBean.getMsg());
                    }
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                dismissDialog();
            }
        });
    }

    private void requestData() {
        HttpParams params = new HttpParams();
        if (!TextUtils.isEmpty(categoriesId)) {
            params.put("categoriesId", categoriesId);
        }
        params.put("limit", 10);
        if (mUserInfoBean != null) {
            params.put("userId", mUserInfoBean.getUser().getUserId());
        } else {
            if (!TextUtils.isEmpty(ExampleUtil.getImei(context, ""))) {
                params.put("uuid", ExampleUtil.getImei(context, ""));
            } else {
                if (!TextUtils.isEmpty(JPushInterface.getUdid(context))) {
                    params.put("uuid", JPushInterface.getUdid(context));
                } else {
                    if (!TextUtils.isEmpty(JPushInterface.getRegistrationID(context))) {
                        params.put("uuid", JPushInterface.getRegistrationID(context));
                    } else {
                        params.put("uuid", System.currentTimeMillis() + "");
                    }
                }
            }
        }
        params.put("discoverType", 2);
        try {
            Logger.e(listBeans.get(listBeans.size() - 1).getTime());
            params.put("startTime", listBeans.get(listBeans.size() - 1).getTime());
        } catch (Exception e) {
        }
        finalOkGo.request(RequestType.POST, Url.FIND_LIST, params, Url.FIND_LIST, new Callback<FindListBean>() {
            @Override
            public void onSuccess(FindListBean findListBean) {
                dismissDialog();
                if (findListBean.getCode() == Contacts.SUCCESS) {
                    if (findListBean.getList() == null || findListBean.getList().size() == 0) {
                    } else {
                        for (int i = 0; i < findListBean.getList().size(); i++) {
                            FindListBean.ListBean item = findListBean.getList().get(i);
                            VideoView videoView = new VideoView(context);
                            VideoDetailHashMap.getIntance().put(item.getId(), videoView);
                            VideoListBean videoListBean = new VideoListBean();
                            videoListBean.setModule(1);
                            videoListBean.setVideoDownloadUrl(item.getContent());
                            videoListBean.setCoverImgUrl(item.getContent() + "?vframe/jpg/offset/1");
                            videoListBean.setTitle(item.getTitle());
                            videoListBean.setComment_num(item.getCommentSum());
                            videoListBean.setPraise_num(item.getLikeSum());
                            videoListBean.setHeadPhoto(item.getAvatar());
                            videoListBean.setNickName(item.getNickname());
                            videoListBean.setTime(item.getCreateTime());
                            videoListBean.setIsLike(item.getIsLike());
                            videoListBean.setAnonymity(0);
                            videoListBean.setUserId(item.getUserId());
                            videoListBean.setContentId(item.getId());
                            listBeans.add(videoListBean);
                        }

                        verticalViewPagerAdapter.notifyDataSetChanged();
                    }
                } else {
                    showImageToas("网络开小差了...");
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                dismissDialog();
            }
        });
    }

    private void startPlay(int position) {
        if (position == listBeans.size() - 3) {
            requestData();
        }
        int count = viewpager.getChildCount();
        for (int i = 0; i < count; i++) {
            View itemView = viewpager.getChildAt(i);
            VerticalViewPagerAdapter.ViewHolder viewHolder = (VerticalViewPagerAdapter.ViewHolder) itemView.getTag();
            if (viewHolder.mPosition == position) {
                VideoListBean tiktokBean = listBeans.get(position);
                VideoView videoView = VideoDetailHashMap.getIntance().get(tiktokBean.getContentId());
                Logger.e(tiktokBean.getVideoDownloadUrl());
                String playUrl = mPreloadManager.getPlayUrl(tiktokBean.getVideoDownloadUrl());
                if (videoView != null) {
                    videoView.setUrl(playUrl);
                    videoView.setMute(false);
                    videoView.start();
                }
                mPlayingPosition = position;
                break;
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    public void OnMessageEvent(String event) {
        String s = event.split(":")[0];
        if (s.equals("finish_video_detail")) {
            finishActivity();
        } else if (s.equals("FindVideoDetailActivity_comment")) {
            if (!TextUtils.isEmpty(comment_et.getText().toString().trim())) {
                if (et_flag.equals("comment")) {
                    showDialog(context, "评论中...");
                    JSONObject jsonObject = new JSONObject();
                    JSONArray jsonArray = new JSONArray();
                    try {
                        for (int i = 0; i < comment_et.getNameList().size(); i++) {
                            JSONObject userJson = new JSONObject();
                            userJson.put("userId", comment_et.getNameList().get(i).getUser_id());
                            userJson.put("nickname", comment_et.getNameList().get(i).getUser_name());
                            jsonArray.put(userJson);
                        }
                        jsonObject.put("remindJson", jsonArray.toString());
                        jsonObject.put("contentId", listBeans.get(commentPosition).getContentId());
                        jsonObject.put("comment", comment_et.getText().toString().trim());
                        jsonObject.put("position", 1);
                        if (listBeans.get(commentPosition).getModule() == 0) {
                            jsonObject.put("type", 1);
                        } else {
                            jsonObject.put("type", 2);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    finalOkGo.requestHead(RequestType.POSTJSONHEAD, Url.COMMENT_SAVE, null, jsonObject.toString(), new Callback<SendCodeBean>() {
                        @Override
                        public void onSuccess(SendCodeBean sendCodeBean) {
                            dismissDialog();
                            if (sendCodeBean.getCode() == Contacts.SUCCESS) {
                                et_flag = "comment";
                                int count = viewpager.getChildCount();
                                for (int i = 0; i < count; i++) {
                                    View itemView = viewpager.getChildAt(i);
                                    VerticalViewPagerAdapter.ViewHolder viewHolder = (VerticalViewPagerAdapter.ViewHolder) itemView.getTag();
                                    if (viewHolder.mPosition == commentPosition) {
                                        viewHolder.comment_tv.setText(listBeans.get(commentPosition).getComment_num() + 1 + "");
                                        break;
                                    }
                                }
                                listBeans.get(commentPosition).setComment_num(listBeans.get(commentPosition).getComment_num() + 1);
                                verticalViewPagerAdapter.notifyDataSetChanged();
                                if (commentPosition == 0) {
                                    if (flag.equals("praise")) {
                                        EventBus.getDefault().post("refresh_comment_sum_praise:" + categoriesId + ":" + dataPosition);
                                        EventBus.getDefault().post("refresh_comment_sum:" + categoriesId + ":" + dataPosition);
                                    } else if (flag.equals("mineAll")) {
                                        EventBus.getDefault().post("refresh_comment_sum_mine:" + categoriesId + ":" + dataPosition);
                                        EventBus.getDefault().post("refresh_comment_sum:" + categoriesId + ":" + dataPosition);
                                    } else if (flag.equals("mineVideo")) {
                                        EventBus.getDefault().post("refresh_find_comment_count:" + dataPosition);
                                        EventBus.getDefault().post("refresh_mine");
                                    } else {
                                        EventBus.getDefault().post("refresh_comment_sum:" + categoriesId + ":" + dataPosition);
                                    }
                                }
                                EventBus.getDefault().post("refresh_find_comment_count:" + listBeans.get(commentPosition).getContentId());
                                replayName = "";
                                replayContent = "";
//                                pageNum = 1;
//                                requestComment(commentPosition);
                                List<CommentListBean.PageBean.ListBean> commentList = new ArrayList<>();
                                for (int i = 0; i < quickAdapter.getCount(); i++) {
                                    commentList.add(quickAdapter.getItem(i));
                                }
                                CommentListBean.PageBean.ListBean bean = new CommentListBean.PageBean.ListBean();
                                bean.setId(sendCodeBean.getCommentId());
                                bean.setComment(comment_et.getText().toString().trim());
                                bean.setContentId(listBeans.get(commentPosition).getContentId());
                                bean.setPosition(1);
                                if (listBeans.get(commentPosition).getModule() == 0) {
                                    bean.setType(1);
                                } else {
                                    bean.setType(2);
                                }
                                bean.setRemindJson(jsonArray.toString());
                                bean.setCreateTime(DateFormatUtil.ms4Date(System.currentTimeMillis()));
                                bean.setAvatar(mUserInfoBean.getUser().getAvatar());
                                bean.setNickname(mUserInfoBean.getUser().getNickname());
                                bean.setUserId(mUserInfoBean.getUser().getUserId());
                                quickAdapter.clear();
                                quickAdapter.add(bean);
                                quickAdapter.addAll(commentList);
                                comment_et.setText("");
                                listView.setSelection(0);
                            } else {
                                if (sendCodeBean.getCode() == Contacts.TOKEN_EMPTY) {
                                } else {
                                    showImageToas(sendCodeBean.getMsg());
                                }
                            }
                        }

                        @Override
                        public void onError(Response<String> response) {
                            super.onError(response);
                            dismissDialog();
                        }
                    });
                } else {
                    showDialog(context, "评论中...");
                    JSONObject jsonObject = new JSONObject();
                    JSONArray jsonArray = new JSONArray();
                    try {
                        for (int i = 0; i < comment_et.getNameList().size(); i++) {
                            JSONObject userJson = new JSONObject();
                            userJson.put("userId", comment_et.getNameList().get(i).getUser_id());
                            userJson.put("nickname", comment_et.getNameList().get(i).getUser_name());
                            jsonArray.put(userJson);
                        }
                        jsonObject.put("remindJson", jsonArray.toString());
                        jsonObject.put("contentId", listBeans.get(commentPosition).getContentId());
                        jsonObject.put("comment", comment_et.getText().toString().trim());
                        jsonObject.put("replyUserId", replyUserId);
                        jsonObject.put("replyCommentId", replyCommentId);
                        jsonObject.put("position", 2);
                        if (listBeans.get(commentPosition).getModule() == 0) {
                            jsonObject.put("type", 1);
                        } else {
                            jsonObject.put("type", 2);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    finalOkGo.requestHead(RequestType.POSTJSONHEAD, Url.COMMENT_SAVE, null, jsonObject.toString(), new Callback<SendCodeBean>() {
                        @Override
                        public void onSuccess(SendCodeBean sendCodeBean) {
                            dismissDialog();
                            if (sendCodeBean.getCode() == Contacts.SUCCESS) {
                                if (flag.equals("mineVideo")) {
                                    EventBus.getDefault().post("refresh_find_comment_count:" + dataPosition);
                                    EventBus.getDefault().post("refresh_mine");
                                }
                                EventBus.getDefault().post("refresh_find_comment_count:" + listBeans.get(commentPosition).getContentId());
                                et_flag = "comment";
                                replayName = "";
                                replayContent = "";
//                                pageNum = 1;
//                                requestComment(commentPosition);
                                if (quickAdapter.getItem(replyPosition).getLowerComment() == null) {
                                    quickAdapter.getItem(replyPosition).setLowerComment(new LinkedList<CommentListBean.PageBean.ListBean.LowerCommentBean>());
                                }
                                CommentListBean.PageBean.ListBean.LowerCommentBean lowerCommentBean = new CommentListBean.PageBean.ListBean.LowerCommentBean();
                                lowerCommentBean.setComment(comment_et.getText().toString().trim());
                                lowerCommentBean.setContentId(listBeans.get(commentPosition).getContentId());
                                lowerCommentBean.setRemindJson(jsonArray.toString());
                                lowerCommentBean.setReplyUserId(Integer.parseInt(replyUserId));
                                lowerCommentBean.setReplyCommentId(Integer.parseInt(replyCommentId));
                                lowerCommentBean.setNickname(mUserInfoBean.getUser().getNickname());
                                lowerCommentBean.setReplyNickname(quickAdapter.getItem(replyPosition).getNickname());
                                lowerCommentBean.setUserId(mUserInfoBean.getUser().getUserId());
                                lowerCommentBean.setReplyUserId(quickAdapter.getItem(replyPosition).getUserId());
                                if(quickAdapter.getItem(replyPosition).getLowerComment().size()>=2){
                                    quickAdapter.getItem(replyPosition).getLowerComment().set(0,lowerCommentBean);
                                }else{
                                    quickAdapter.getItem(replyPosition).getLowerComment().addFirst(lowerCommentBean);
                                }
                                quickAdapter.getItem(replyPosition).setCommentSum(quickAdapter.getItem(replyPosition).getCommentSum() + 1);
                                quickAdapter.notifyDataSetChanged();
                                comment_et.setText("");
                            } else {
                                if (sendCodeBean.getCode() == Contacts.TOKEN_EMPTY) {
                                } else {
                                    showImageToas(sendCodeBean.getMsg());
                                }
                            }
                        }

                        @Override
                        public void onError(Response<String> response) {
                            super.onError(response);
                            dismissDialog();
                        }
                    });
                }
            } else {
//                showImageToas("请填写点内容吧");
            }
        } else if ("comment_detial_sub".equals(s) || "comment_detial_add".equals(s)) {
            if (top_ll.getVisibility() == View.VISIBLE) {
                if (s.equals("comment_detial_sub")) {
                    EventBus.getDefault().post("delete_find_comment_count:" + dataPosition);
                    int count = viewpager.getChildCount();
                    for (int i = 0; i < count; i++) {
                        View itemView = viewpager.getChildAt(i);
                        VerticalViewPagerAdapter.ViewHolder viewHolder = (VerticalViewPagerAdapter.ViewHolder) itemView.getTag();
                        if (viewHolder.mPosition == commentPosition) {
                            viewHolder.comment_tv.setText(listBeans.get(commentPosition).getComment_num() - 1 + "");
                            break;
                        }
                    }
                    listBeans.get(commentPosition).setComment_num(listBeans.get(commentPosition).getComment_num() - 1);
                    verticalViewPagerAdapter.notifyDataSetChanged();
                } else if (s.equals("comment_detial_add")) {
                    if ((event.split(":")[1] + "").equals("comment")) {
                        EventBus.getDefault().post("refresh_find_comment_count:" + dataPosition);
                        int count = viewpager.getChildCount();
                        for (int i = 0; i < count; i++) {
                            View itemView = viewpager.getChildAt(i);
                            VerticalViewPagerAdapter.ViewHolder viewHolder = (VerticalViewPagerAdapter.ViewHolder) itemView.getTag();
                            if (viewHolder.mPosition == commentPosition) {
                                viewHolder.comment_tv.setText(listBeans.get(commentPosition).getComment_num() + 1 + "");
                                break;
                            }
                        }
                        listBeans.get(commentPosition).setComment_num(listBeans.get(commentPosition).getComment_num() + 1);
                        verticalViewPagerAdapter.notifyDataSetChanged();
                    }
                }
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        VideoViewManager.instance().pause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        VideoViewManager.instance().resume();
    }

    @Override
    protected void onDestroy() {

        super.onDestroy();


        //清除缓存，实际使用可以不需要清除，这里为了方便测试
//        ProxyVideoCacheManager.clearAllCache(this);
    }

    @Override
    public void onBackPressed() {
        onBack();
//        super.onBackPressed();
    }

    /**
     * 将播放器从父控件中移除
     */
    private void removePlayerFormParent(VideoView mVideoView) {
        ViewParent parent = mVideoView.getParent();
        if (parent instanceof FrameLayout) {
            ((FrameLayout) parent).removeView(mVideoView);
        }
    }

    private void tokenVerify() {
        HttpParams params = new HttpParams();
        params.put("token", (String) SharedPreferencesHelp.get("token", ""));
        finalOkGo.requestHead(RequestType.POSTHEAD, Url.VERIFY_TOKEN, params, Url.VERIFY_TOKEN, new Callback<SendCodeBean>() {
            @Override
            public void onSuccess(SendCodeBean sendCodeBean) {
                if (sendCodeBean.getCode() == Contacts.SUCCESS) {
                    commentDialogFragment = new DetailCommentDialog();
                    commentDialogFragment.setCommentFlag("FindVideoDetailActivity");
                    commentDialogFragment.show(getFragmentManager(), "DetailCommentDialog");
                }
            }

            @Override
            public void onError(Response response) {
                super.onError(response);
            }
        });
    }

    @Override
    public String getCommentText() {
        return comment_et.getText().toString();
    }

    @Override
    public String getReplayName() {
        return replayName;
    }

    @Override
    public String getReplayContent() {
        return replayContent;
    }

    @Override
    public void setCommentText(String commentTextTemp) {
        if(!TextUtils.isEmpty(commentTextTemp)){
            comment_et.setRichText(commentTextTemp);
        }else{
            comment_et.setText(commentTextTemp);
        }
    }

    @Override
    public List<UserModel> getNameList() {
        for (int i = 0; i < comment_et.getNameList().size(); i++) {
            comment_et.getNameList().get(i).setUser_name("@" + comment_et.getNameList().get(i).getUser_name());
        }
        return comment_et.getNameList();
    }

    @Override
    public void setNameList(List<UserModel> nameList) {
        comment_et.setNameList(nameList);
    }


    @Override
    public void onCommentClick(int position) {
        View dialog_video_comment = View.inflate(context, R.layout.dialog_video_comment, null);
        container_framelayout.addView(dialog_video_comment);
        commentPosition = position;
        et_flag = "comment";
        int container_height = container_framelayout.getMeasuredHeight();
        container_framelayout
                .animate()
                .translationY(-container_height)
                .setDuration(200)
                .start();
        top_ll.setVisibility(View.VISIBLE);
        listView = dialog_video_comment.findViewById(R.id.listview);
        RelativeLayout comment_rl = dialog_video_comment.findViewById(R.id.comment_rl);
        empty_img = dialog_video_comment.findViewById(R.id.empty_img);
        comment_et = dialog_video_comment.findViewById(R.id.comment_et);

        nameList = new ArrayList<>();
        //直接使用RichTextView
        comment_et.setAtColor(Color.parseColor(getString(R.string.remind_color)));
        comment_et.setLinkColor(Color.BLUE);
        //所有配置完成后才设置text
        comment_et.setNameList(nameList);

        ITextViewShow iTextViewShow = new ITextViewShow() {
            @Override
            public void setText(CharSequence charSequence) {
                comment_et.setText(charSequence);
            }

            @Override
            public CharSequence getText() {
                return comment_et.getText();
            }

            @Override
            public void setMovementMethod(MovementMethod movementMethod) {
                comment_et.setMovementMethod(movementMethod);
            }

            @Override
            public void setAutoLinkMask(int flag) {
                comment_et.setAutoLinkMask(flag);
            }


            @Override
            public ClickAtUserSpan getCustomClickAtUserSpan(Context context, UserModel userModel, int color, SpanAtUserCallBack spanClickCallBack) {
                return null;
            }

            @Override
            public ClickTopicSpan getCustomClickTopicSpan(Context context, TopicModel topicModel, int color, SpanTopicCallBack spanTopicCallBack) {
                return null;
            }

            @Override
            public LinkSpan getCustomLinkSpan(Context context, String url, int color, SpanUrlCallBack spanUrlCallBack) {
                return null;
            }

            @Override
            public int emojiSize() {
                return 0;
            }

            @Override
            public int verticalAlignment() {
                return DynamicDrawableSpan.ALIGN_BOTTOM;
            }
        };

        CircleImageView image = dialog_video_comment.findViewById(R.id.image);
        if (mUserInfoBean != null) {
            Glide.with(context)
                    .load(mUserInfoBean.getUser().getAvatar())
                    .error(R.mipmap.icon_no_head)
                    .into(image);
        } else {
            Glide.with(context)
                    .load(R.mipmap.icon_no_head)
                    .error(R.mipmap.icon_no_head)
                    .into(image);
        }

        comment_rl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Utils.isDoubleClick()) {
                    return;
                }
                et_flag = "comment";
                replayName = "";
                replayContent = "";
                tokenVerify();
            }
        });

        comment_et.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Utils.isDoubleClick()) {
                    return;
                }
                et_flag = "comment";
                replayName = "";
                replayContent = "";
                tokenVerify();
            }
        });

        refreshLayout = dialog_video_comment.findViewById(R.id.refreshLayout);
        refreshLayout.setOnRefreshLoadMoreListener(this);
        refreshLayout.setRefreshHeader(new MaterialHeader(context).setColorSchemeResources(R.color.common_color));
        refreshLayout.setEnableAutoLoadMore(true);

        quickAdapter = new QuickAdapter<CommentListBean.PageBean.ListBean>(context, R.layout.item_comment_receive) {
            @Override
            protected void convert(BaseAdapterHelper helper, CommentListBean.PageBean.ListBean item) {
                helper.getView(R.id.item_ll).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (Utils.isDoubleClick()) {
                            return;
                        }
                        Bundle bundle1 = new Bundle();
                        bundle1.putString("userId", item.getUserId() + "");
                        bundle1.putString("name", item.getNickname());
                        bundle1.putString("id", item.getId() + "");
                        bundle1.putString("content", item.getComment());
                        bundle1.putString("time", item.getCreateTime());
                        bundle1.putString("head", item.getAvatar());
                        bundle1.putString("praise", item.getLikeSum() + "");
                        bundle1.putString("commentNum", item.getCommentSum() + "");
                        bundle1.putString("contentId", listBeans.get(position).getContentId() + "");
                        bundle1.putString("content_userid", listBeans.get(position).getUserId() + "");
                        bundle1.putString("content_anonymity", listBeans.get(position).getAnonymity() + "");
                        bundle1.putString("replyCommentId", item.getId() + "");
                        bundle1.putString("isLike", item.getIsLike() + "");
                        if (listBeans.get(position).getModule() == 0) {
                            bundle1.putString("module", "1");
                        } else {
                            bundle1.putString("module", "2");
                        }
                        CommentRemindJsonBean commentRemindJsonBean = new CommentRemindJsonBean();
                        List<RemindJson> remindJsons = GsonUtil.jsonToList(item.getRemindJson(), RemindJson.class);
                        commentRemindJsonBean.setList(remindJsons);
                        bundle1.putSerializable("commentRemindJsonBean", commentRemindJsonBean);
                        startActivity(CommentDetailActivity.class, bundle1);
                    }
                });

                CircleImageView head_photo = helper.getView(R.id.head_photo);
                Glide.with(context)
                        .load(item.getAvatar())
                        .dontAnimate()
                        .placeholder(R.mipmap.icon_no_head)
                        .into(head_photo);
                head_photo.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (Utils.isDoubleClick()) {
                            return;
                        }
                        Bundle bundle1 = new Bundle();
                        bundle1.putString("userId", item.getUserId() + "");
                        bundle1.putString("userName", item.getNickname() + "");
                        startActivity(OtherInfoActivity.class, bundle1);
                    }
                });

                helper.setText(R.id.name, item.getNickname());

                RichTextView richTextView = helper.getView(R.id.content);
                List<UserModel> list = new ArrayList<>();
                if (!TextUtils.isEmpty(item.getRemindJson()) && !"[]".equals(item.getRemindJson())) {
                    List<RemindJson> remindJsons = GsonUtil.jsonToList(item.getRemindJson(), RemindJson.class);
                    if (remindJsons != null) {
                        for (int i = 0; i < remindJsons.size(); i++) {
                            UserModel userModel = new UserModel();
                            userModel.setUser_name(remindJsons.get(i).getNickname());
                            userModel.setUser_id(remindJsons.get(i).getUserId() + "");
                            list.add(userModel);
                        }
                    }
                }
                //直接使用RichTextView
                richTextView.setAtColor(Color.parseColor(getString(R.string.remind_color)));
                richTextView.setLinkColor(Color.BLUE);
                richTextView.setSpanAtUserCallBackListener(spanAtUserCallBack);
                //所有配置完成后才设置text
                if (item.getWeight() == 1) {
                    richTextView.setRichTextUser("[icon_comment_official] " + item.getComment(), list);
                } else if (item.getWeight() == -2) {
                    richTextView.setRichTextUser("[icon_comment_god] " + item.getComment(), list);
                } else {
                    richTextView.setRichTextUser(item.getComment(), list);
                }

                TextView praise = helper.getView(R.id.praise);
                if (item.getIsLike() == 0) {
                    praise.setCompoundDrawablesWithIntrinsicBounds(drawable_unselect, null, null, null);
                } else {
                    praise.setCompoundDrawablesWithIntrinsicBounds(drawable_select, null, null, null);
                }
                praise.setText(item.getLikeSum() + "");
                praise.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (Utils.isDoubleClick()) {
                            return;
                        }
                        if (item.getIsLike() == 1) {
                            praise.setEnabled(false);
                            showDialog(context, "取消中...");
                            JSONObject jsonObject = new JSONObject();
                            try {
                                jsonObject.put("contentId", item.getId());
                                if (listBeans.get(position).getModule() == 0) {
                                    jsonObject.put("module", 1);
                                } else {
                                    jsonObject.put("module", 2);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            finalOkGo.requestHead(RequestType.POSTJSONHEAD, Url.COMMENT_CANCEL_PRAISE, null, jsonObject.toString(), new Callback<SendCodeBean>() {
                                @Override
                                public void onSuccess(SendCodeBean sendCodeBean) {
                                    dismissDialog();
                                    praise.setEnabled(true);
                                    if (sendCodeBean.getCode() == Contacts.SUCCESS) {
                                        item.setIsLike(0);
                                        item.setLikeSum(item.getLikeSum() - 1);
                                        notifyDataSetChanged();
                                    } else {
                                        if (sendCodeBean.getCode() == Contacts.TOKEN_EMPTY) {
                                        } else {
                                            showImageToas(sendCodeBean.getMsg());
                                        }
                                    }
                                }

                                @Override
                                public void onError(Response<String> response) {
                                    super.onError(response);
                                    dismissDialog();
                                    praise.setEnabled(true);
                                }
                            });
                        } else {
                            praise.setEnabled(false);
                            showDialog(context, "点赞中...");
                            JSONObject jsonObject = new JSONObject();
                            try {
                                jsonObject.put("contentId", item.getId());
                                if (listBeans.get(position).getModule() == 0) {
                                    jsonObject.put("module", 1);
                                } else {
                                    jsonObject.put("module", 2);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            finalOkGo.requestHead(RequestType.POSTJSONHEAD, Url.COMMENT_PRAISE, null, jsonObject.toString(), new Callback<SendCodeBean>() {
                                @Override
                                public void onSuccess(SendCodeBean sendCodeBean) {
                                    dismissDialog();
                                    praise.setEnabled(true);
                                    if (sendCodeBean.getCode() == Contacts.SUCCESS) {
                                        item.setIsLike(1);
                                        item.setLikeSum(item.getLikeSum() + 1);
                                        notifyDataSetChanged();
                                    } else {
                                        if (sendCodeBean.getCode() == Contacts.TOKEN_EMPTY) {
                                        } else {
                                            showImageToas(sendCodeBean.getMsg());
                                        }
                                    }
                                }

                                @Override
                                public void onError(Response<String> response) {
                                    super.onError(response);
                                    dismissDialog();
                                    praise.setEnabled(true);
                                }
                            });
                        }
                    }
                });


                TextView comment = helper.getView(R.id.comment);
                comment.setText(item.getCommentSum() + "");
                comment.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (Utils.isDoubleClick()) {
                            return;
                        }
                        replyUserId = item.getUserId() + "";
                        replyCommentId = item.getId() + "";
                        et_flag = "receive";
                        replayName = item.getNickname();
                        replayContent = item.getComment();
                        replyPosition = helper.getPosition();
                        tokenVerify();
                    }
                });

                TextView time = helper.getView(R.id.time);
                timecha(item.getCreateTime(), time);

                LinearLayout receive_ll = helper.getView(R.id.receive_ll);
                TextView more = helper.getView(R.id.more);
                if (item.getLowerComment() != null && item.getLowerComment().size() != 0) {
                    if (item.getCommentSum() > 2) {
                        more.setVisibility(View.VISIBLE);
                        more.setText("查看全部" + item.getCommentSum() + "条回复");
                    } else {
                        more.setVisibility(View.GONE);
                    }
                    receive_ll.setVisibility(View.VISIBLE);
                    receive_ll.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            if (Utils.isDoubleClick()) {
                                return;
                            }
                            Bundle bundle1 = new Bundle();
                            bundle1.putString("userId", item.getUserId() + "");
                            bundle1.putString("name", item.getNickname());
                            bundle1.putString("id", item.getId() + "");
                            bundle1.putString("content", item.getComment());
                            bundle1.putString("time", item.getCreateTime());
                            bundle1.putString("head", item.getAvatar());
                            bundle1.putString("praise", item.getLikeSum() + "");
                            bundle1.putString("commentNum", item.getCommentSum() + "");
                            bundle1.putString("contentId", listBeans.get(position).getContentId() + "");
                            bundle1.putString("content_userid", listBeans.get(position).getUserId() + "");
                            bundle1.putString("content_anonymity", listBeans.get(position).getAnonymity() + "");
                            bundle1.putString("replyCommentId", item.getId() + "");
                            bundle1.putString("isLike", item.getIsLike() + "");
                            if (listBeans.get(position).getModule() == 0) {
                                bundle1.putString("module", "1");
                            } else {
                                bundle1.putString("module", "2");
                            }
                            CommentRemindJsonBean commentRemindJsonBean = new CommentRemindJsonBean();
                            List<RemindJson> remindJsons = GsonUtil.jsonToList(item.getRemindJson(), RemindJson.class);
                            commentRemindJsonBean.setList(remindJsons);
                            bundle1.putSerializable("commentRemindJsonBean", commentRemindJsonBean);
                            bundle1.putInt("weight", item.getWeight());
                            startActivity(CommentDetailActivity.class, bundle1);
                        }
                    });

                    XListView receive_listview = helper.getView(R.id.receive_listview);

                    QuickAdapter<CommentListBean.PageBean.ListBean.LowerCommentBean> child_adapter =
                            new QuickAdapter<CommentListBean.PageBean.ListBean.LowerCommentBean>(context, R.layout.item_receive, item.getLowerComment()) {
                                @Override
                                protected void convert(BaseAdapterHelper helper, CommentListBean.PageBean.ListBean.LowerCommentBean item) {
                                    TextView textView = helper.getView(R.id.textview);
                                    if (item.getUserId() == listBeans.get(position).getUserId()) {
                                        List<UserModel> list = new ArrayList<>();
                                        if (!TextUtils.isEmpty(item.getRemindJson()) && !"[]".equals(item.getRemindJson())) {
                                            List<RemindJson> remindJsons = GsonUtil.jsonToList(item.getRemindJson(), RemindJson.class);
                                            if (remindJsons != null) {
                                                for (int i = 0; i < remindJsons.size(); i++) {
                                                    UserModel userModel = new UserModel();
                                                    userModel.setUser_name(remindJsons.get(i).getNickname());
                                                    userModel.setUser_id(remindJsons.get(i).getUserId() + "");
                                                    list.add(userModel);
                                                }
                                            }
                                        }
                                        Spannable spannable = TextCommonUtils.getAtText(context, list,
                                                null,
                                                item.getNickname() + "(主人回复)：" + item.getComment(),
                                                iTextViewShow,
                                                true,
                                                Color.parseColor(getString(R.string.remind_color)),
                                                0,
                                                spanAtUserCallBack,
                                                null);
                                        Spannable spannable1 = new SpannableString(spannable);
                                        spannable1.setSpan(span, 0, (item.getNickname() + "(主人回复)：").length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                                        textView.setText(spannable1);
                                    } else {
                                        List<UserModel> list = new ArrayList<>();
                                        if (!TextUtils.isEmpty(item.getRemindJson()) && !"[]".equals(item.getRemindJson())) {
                                            List<RemindJson> remindJsons = GsonUtil.jsonToList(item.getRemindJson(), RemindJson.class);
                                            if (remindJsons != null) {
                                                for (int i = 0; i < remindJsons.size(); i++) {
                                                    UserModel userModel = new UserModel();
                                                    userModel.setUser_name(remindJsons.get(i).getNickname());
                                                    userModel.setUser_id(remindJsons.get(i).getUserId() + "");
                                                    list.add(userModel);
                                                }
                                            }
                                        }
                                        Spannable spannable = TextCommonUtils.getAtText(context, list,
                                                null,
                                                item.getNickname() + "回复" + item.getReplyNickname() + ":" + item.getComment(),
                                                iTextViewShow,
                                                true,
                                                Color.parseColor(getString(R.string.remind_color)),
                                                0,
                                                spanAtUserCallBack,
                                                null);

                                        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(spannable);
                                        spannableStringBuilder.setSpan(span, 0, item.getNickname().length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
                                        spannableStringBuilder.setSpan(span1, item.getNickname().length(), item.getNickname().length() + 2, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
                                        spannableStringBuilder.setSpan(span2, item.getNickname().length() + 2, item.getNickname().length() + 2 + item.getReplyNickname().length() + 1, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
                                        textView.setText(spannableStringBuilder);
                                    }
                                }
                            };

                    receive_listview.setAdapter(child_adapter);
                    receive_listview.setFocusable(false);
                    receive_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                            if (Utils.isDoubleClick()) {
                                return;
                            }
                            Bundle bundle1 = new Bundle();
                            bundle1.putString("userId", item.getUserId() + "");
                            bundle1.putString("name", item.getNickname());
                            bundle1.putString("id", item.getId() + "");
                            bundle1.putString("content", item.getComment());
                            bundle1.putString("time", item.getCreateTime());
                            bundle1.putString("head", item.getAvatar());
                            bundle1.putString("praise", item.getLikeSum() + "");
                            bundle1.putString("commentNum", item.getCommentSum() + "");
                            bundle1.putString("contentId", listBeans.get(position).getContentId() + "");
                            bundle1.putString("content_userid", listBeans.get(position).getUserId() + "");
                            bundle1.putString("content_anonymity", listBeans.get(position).getAnonymity() + "");
                            bundle1.putString("replyCommentId", item.getId() + "");
                            bundle1.putString("isLike", item.getIsLike() + "");
                            if (listBeans.get(position).getModule() == 0) {
                                bundle1.putString("module", "1");
                            } else {
                                bundle1.putString("module", "2");
                            }
                            CommentRemindJsonBean commentRemindJsonBean = new CommentRemindJsonBean();
                            List<RemindJson> remindJsons = GsonUtil.jsonToList(item.getRemindJson(), RemindJson.class);
                            commentRemindJsonBean.setList(remindJsons);
                            bundle1.putSerializable("commentRemindJsonBean", commentRemindJsonBean);
                            bundle1.putInt("weight", item.getWeight());
                            startActivity(CommentDetailActivity.class, bundle1);
                        }
                    });
                } else {
                    receive_ll.setVisibility(View.GONE);
                }
            }
        };
        listView.setAdapter(quickAdapter);

        pageNum = 1;
        requestComment(position);
    }

    private void requestComment(int position) {
        HttpParams params = new HttpParams();
        params.put("contentId", listBeans.get(position).getContentId());
        if (listBeans.get(position).getModule() == 0) {
            params.put("type", 1);
        } else {
            params.put("type", 2);
        }
        if (mUserInfoBean != null) {
            params.put("userId", mUserInfoBean.getUser().getUserId());
        }
        params.put("position", 1);
        params.put("limit", pageSize);
        params.put("page", pageNum++);
        finalOkGo.request(RequestType.POST, Url.GET_COMMENT_LIST, params, Url.GET_COMMENT_LIST, new Callback<CommentListBean>() {
            @Override
            public void onSuccess(CommentListBean commentListBean) {
                dismissDialog();
                if (commentListBean.getCode() == Contacts.SUCCESS) {
                    if (pageNum - 1 == 1) {
                        if (commentListBean.getPage().getList() == null || commentListBean.getPage().getList().size() == 0) {
                            empty_img.setVisibility(View.VISIBLE);
                        } else {
                            empty_img.setVisibility(View.GONE);
                        }
                        quickAdapter.clear();
                        quickAdapter.addAll(commentListBean.getPage().getList());
                    } else {
                        quickAdapter.addAll(commentListBean.getPage().getList());
                    }

                    refreshLayout.finishRefresh();
                    refreshLayout.finishLoadMore();
                    quickAdapter.notifyDataSetChanged();

                    int pagecount;
                    if (commentListBean.getPage().getTotalCount() % pageSize == 0) {
                        pagecount = commentListBean.getPage().getTotalCount() / pageSize;
                    } else {
                        pagecount = commentListBean.getPage().getTotalCount() / pageSize + 1;
                    }

                    if (pageNum > pagecount) {
                        refreshLayout.setNoMoreData(true);
                        refreshLayout.finishLoadMoreWithNoMoreData();
                    } else {
                        refreshLayout.setNoMoreData(false);
                    }

                } else {
                    if (pageNum - 1 == 1) {
                        empty_img.setVisibility(View.VISIBLE);
                    } else {
                        empty_img.setVisibility(View.GONE);
                    }
                    if (commentListBean.getCode() == Contacts.TOKEN_EMPTY) {
                    } else {
                        showImageToas(commentListBean.getMsg());
                    }
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                dismissDialog();
                if (pageNum - 1 == 1) {
                    empty_img.setVisibility(View.VISIBLE);
                } else {
                    empty_img.setVisibility(View.GONE);
                }
            }
        });
    }


    @Override
    public void onPraiseClick(int position) {
        if (listBeans.get(position).getIsLike() == 1) {
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("contentId", listBeans.get(position).getContentId());
                if (listBeans.get(position).getModule() == 0) {
                    jsonObject.put("module", 1);
                } else {
                    jsonObject.put("module", 2);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            finalOkGo.requestHead(RequestType.POSTJSONHEAD, Url.CANCEL_PRAISE_HOME, null, jsonObject.toString(), new Callback<SendCodeBean>() {
                @Override
                public void onSuccess(SendCodeBean sendCodeBean) {
                    if (sendCodeBean.getCode() == Contacts.SUCCESS) {
                        int count = viewpager.getChildCount();
                        for (int i = 0; i < count; i++) {
                            View itemView = viewpager.getChildAt(i);
                            VerticalViewPagerAdapter.ViewHolder viewHolder = (VerticalViewPagerAdapter.ViewHolder) itemView.getTag();
                            if (viewHolder.mPosition == position) {
                                viewHolder.praise_iv.setImageResource(R.mipmap.item_praise);
                                viewHolder.praise_tv.setText(listBeans.get(position).getPraise_num() - 1 + "");
                                break;
                            }
                        }
                        listBeans.get(position).setIsLike(0);
                        listBeans.get(position).setPraise_num(listBeans.get(position).getPraise_num() - 1);
                        verticalViewPagerAdapter.notifyDataSetChanged();
                        if (position == 0) {
                            if (flag.equals("praise")) {
                                EventBus.getDefault().post("refresh_cancel_praise_search:" + categoriesId + ":" + dataPosition);
                                EventBus.getDefault().post("refresh_cancel_praise:" + categoriesId + ":" + dataPosition);
                            } else if (flag.equals("mineAll")) {
                                EventBus.getDefault().post("refresh_cancel_praise_mine:" + categoriesId + ":" + dataPosition);
                                EventBus.getDefault().post("refresh_cancel_praise:" + categoriesId + ":" + dataPosition);
                            } else if (flag.equals("mineVideo")) {
                                EventBus.getDefault().post("refresh_find_cancel_praise:" + dataPosition);
                                EventBus.getDefault().post("refresh_mine");
                            } else {
                                EventBus.getDefault().post("refresh_cancel_praise:" + categoriesId + ":" + dataPosition);
                            }
                        }
                        EventBus.getDefault().post("refresh_find_cancel_praise:" + listBeans.get(position).getContentId());

                    } else {
                        if (sendCodeBean.getCode() == Contacts.TOKEN_EMPTY) {
                        } else {
                            showImageToas(sendCodeBean.getMsg());
                        }
                    }
                }

                @Override
                public void onError(Response<String> response) {
                    super.onError(response);
                }
            });
        } else {
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("contentId", listBeans.get(position).getContentId());
                if (listBeans.get(position).getModule() == 0) {
                    jsonObject.put("module", 1);
                } else {
                    jsonObject.put("module", 2);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            finalOkGo.requestHead(RequestType.POSTJSONHEAD, Url.PRAISE_HOME, null, jsonObject.toString(), new Callback<SendCodeBean>() {
                @Override
                public void onSuccess(SendCodeBean sendCodeBean) {
                    if (sendCodeBean.getCode() == Contacts.SUCCESS) {
                        int count = viewpager.getChildCount();
                        for (int i = 0; i < count; i++) {
                            View itemView = viewpager.getChildAt(i);
                            VerticalViewPagerAdapter.ViewHolder viewHolder = (VerticalViewPagerAdapter.ViewHolder) itemView.getTag();
                            if (viewHolder.mPosition == position) {
                                viewHolder.praise_tv.setText(listBeans.get(position).getPraise_num() + 1 + "");
                                viewHolder.praise_iv.setImageResource(R.mipmap.icon_praise_select);
                                break;
                            }
                        }
                        listBeans.get(position).setIsLike(1);
                        listBeans.get(position).setPraise_num(listBeans.get(position).getPraise_num() + 1);
                        verticalViewPagerAdapter.notifyDataSetChanged();
                        if (position == 0) {
                            if (flag.equals("praise")) {
                                EventBus.getDefault().post("refresh_praise_search:" + categoriesId + ":" + dataPosition);
                                EventBus.getDefault().post("refresh_praise:" + categoriesId + ":" + dataPosition);
                            } else if (flag.equals("mineAll")) {
                                EventBus.getDefault().post("refresh_praise_mine:" + categoriesId + ":" + dataPosition);
                                EventBus.getDefault().post("refresh_praise:" + categoriesId + ":" + dataPosition);
                            } else if (flag.equals("mineVideo")) {
                                EventBus.getDefault().post("refresh_find_praise:" + dataPosition);
                                EventBus.getDefault().post("refresh_mine");
                            } else {
                                EventBus.getDefault().post("refresh_praise:" + categoriesId + ":" + dataPosition);
                            }
                        }
                        EventBus.getDefault().post("refresh_find_praise:" + listBeans.get(position).getContentId());
                    } else {
                        if (sendCodeBean.getCode() == Contacts.TOKEN_EMPTY) {
                        } else {
                            showImageToas(sendCodeBean.getMsg());
                        }
                    }
                }

                @Override
                public void onError(Response<String> response) {
                    super.onError(response);
                }
            });
        }
    }

    @Override
    public void onShareClick(int position) {
        showDialog(context, null);
        JSONObject jsonObject1 = new JSONObject();
        try {
            jsonObject1.put("contentId", listBeans.get(position).getContentId());
            if (listBeans.get(position).getModule() == 0) {
                jsonObject1.put("module", 1);
            } else {
                jsonObject1.put("module", 2);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (listBeans.get(position).getModule() == 0) {
            finalOkGo.requestHead(RequestType.POSTJSONHEAD, Url.SHARE_DATA, null, jsonObject1.toString(), new Callback<ShareDataBean>() {
                @Override
                public void onSuccess(ShareDataBean shareDataBean) {
                    dismissDialog();
                    if (shareDataBean.getCode() == Contacts.SUCCESS) {
                        sharePosition = position;
                        showShareDialog(shareDataBean, 1);
                    } else {
                        if (shareDataBean.getCode() == Contacts.TOKEN_EMPTY) {
                        } else {
                            showImageToas(shareDataBean.getMsg());
                        }
                    }

                }

                @Override
                public void onError(Response<String> response) {
                    super.onError(response);
                    dismissDialog();
                }
            });
        } else {
            finalOkGo.requestHead(RequestType.POSTJSONHEAD, Url.SHARE_DATA, null, jsonObject1.toString(), new Callback<ShareFindBean>() {
                @Override
                public void onSuccess(ShareFindBean shareDataBean) {
                    dismissDialog();
                    if (shareDataBean.getCode() == Contacts.SUCCESS) {
                        sharePosition = position;
                        showFindShareDialog(shareDataBean, 2);
                    } else {
                        if (shareDataBean.getCode() == Contacts.TOKEN_EMPTY) {
                        } else {
                            showImageToas(shareDataBean.getMsg());
                        }
                    }

                }

                @Override
                public void onError(Response<String> response) {
                    super.onError(response);
                    dismissDialog();
                }
            });
        }

    }

    @Override
    public void toDetail(int position) {
    }

    private void showFindShareDialog(ShareFindBean shareDataBean, int moduleInt) {
        this.moduleInt = moduleInt;

        DialogUtil.getInstance().showBottomDialog(context, R.layout.dialog_share);
        LinearLayout dialog_share = (LinearLayout) DialogUtil.getInstance().dialog_bottom_layout;
        dialog_share.findViewById(R.id.close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Utils.isDoubleClick()) {
                    return;
                }
                DialogUtil.getInstance().dialog_bottom.dismiss();
            }
        });

        dialog_share.findViewById(R.id.share_wechat).setOnClickListener(view -> {
            if (Utils.isDoubleClick()) {
                return;
            }
            DialogUtil.getInstance().dialog_bottom.dismiss();
            WXShareUtil wxShareUtil = new WXShareUtil(context);
            wxShareUtil.registerWx();
            WechatLoginUtil.getInstance().setWechatCallBack(FindVideoDetailActivity.this);
            String url = "";
            if (shareDataBean.getDiscover().getType() == 2) {
                url = shareDataBean.getDiscover().getContent() + "?vframe/jpg/offset/1";
            } else if (shareDataBean.getDiscover().getType() == 1) {
                url = shareDataBean.getDiscover().getImage().split("\\|")[0] + "?imageView2/2/w/100";
            } else {
                url = "";
            }
            wxShareUtil.share(shareDataBean.getUrl(),
                    shareDataBean.getDiscover().getTitle(),
                    "",
                    url, wxShareUtil.SHARETOFRIEND);
        });

        dialog_share.findViewById(R.id.share_wechat_friend).setOnClickListener(view -> {
            if (Utils.isDoubleClick()) {
                return;
            }
            DialogUtil.getInstance().dialog_bottom.dismiss();
            WXShareUtil wxShareUtil = new WXShareUtil(context);
            wxShareUtil.registerWx();
            WechatLoginUtil.getInstance().setWechatCallBack(FindVideoDetailActivity.this);
            String url = "";
            if (shareDataBean.getDiscover().getType() == 2) {
                url = shareDataBean.getDiscover().getContent() + "?vframe/jpg/offset/1";
            } else if (shareDataBean.getDiscover().getType() == 1) {
                url = shareDataBean.getDiscover().getImage().split("\\|")[0] + "?imageView2/2/w/100";
            } else {
                url = "";
            }
            wxShareUtil.share(shareDataBean.getUrl(),
                    shareDataBean.getDiscover().getTitle(),
                    "",
                    url, wxShareUtil.SHARETOPYQ);
        });

        dialog_share.findViewById(R.id.share_qq).setOnClickListener(view -> {
            if (Utils.isDoubleClick()) {
                return;
            }
            DialogUtil.getInstance().dialog_bottom.dismiss();
            mTencent = Tencent.createInstance(Config.QQ_APP_ID, ContextUtil.getContext());
            Bundle params = new Bundle();
            params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
            params.putString(QQShare.SHARE_TO_QQ_TITLE, shareDataBean.getDiscover().getTitle());
            params.putString(QQShare.SHARE_TO_QQ_SUMMARY, "");
            params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, shareDataBean.getUrl());
            mTencent.shareToQQ(FindVideoDetailActivity.this, params, new BaseUiListener());
            shareSucess();
        });

        dialog_share.findViewById(R.id.share_qq_space).setOnClickListener(view -> {
            if (Utils.isDoubleClick()) {
                return;
            }
            DialogUtil.getInstance().dialog_bottom.dismiss();
            mTencent = Tencent.createInstance(Config.QQ_APP_ID, context);
            Bundle params = new Bundle();
            params.putInt(QzonePublish.PUBLISH_TO_QZONE_KEY_TYPE, QzonePublish.PUBLISH_TO_QZONE_TYPE_PUBLISHMOOD);
            params.putString(QzonePublish.PUBLISH_TO_QZONE_SUMMARY, shareDataBean.getDiscover().getTitle() + "\n" + shareDataBean.getUrl());//选填
            mTencent.publishToQzone(FindVideoDetailActivity.this, params, new BaseUiListener());
            shareSucess();
        });

        dialog_share.findViewById(R.id.share_weibo).setOnClickListener(view -> {
            if (Utils.isDoubleClick()) {
                return;
            }
            DialogUtil.getInstance().dialog_bottom.dismiss();
            WbSdk.install(ContextUtil.getContext(), new AuthInfo(ContextUtil.getContext(), Config.SINA_APP_KEY, Config.REDIRECT_URL, ""));
            WbShareHandler shareHandler = new WbShareHandler(FindVideoDetailActivity.this);
            shareHandler.registerApp();
            WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
            weiboMessage.textObject = getTextObj(shareDataBean.getUrl(), shareDataBean.getDiscover().getTitle());
            shareHandler.shareMessage(weiboMessage, false);
            shareSucess();
        });

        dialog_share.findViewById(R.id.copy_link).setOnClickListener(view -> {
            if (Utils.isDoubleClick()) {
                return;
            }
            DialogUtil.getInstance().dialog_bottom.dismiss();
            ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
            // 创建一个剪贴数据集，包含一个普通文本数据条目（需要复制的数据）
            ClipData clipData = ClipData.newPlainText(null, shareDataBean.getUrl());
            // 把数据集设置（复制）到剪贴板
            clipboard.setPrimaryClip(clipData);
            showToast("链接已复制");
        });

        ImageView copy_text_iv = dialog_share.findViewById(R.id.copy_text_iv);
        copy_text_iv.setImageResource(R.mipmap.download_video);
        TextView copy_text_tv = dialog_share.findViewById(R.id.copy_text_tv);
        copy_text_tv.setText("下载视频");

        dialog_share.findViewById(R.id.copy_text).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogUtil.getInstance().dialog_bottom.dismiss();
                File file = new File(Utils.getPickerFileDirectory(context, "choupai_video"),
                        shareDataBean.getDiscover().getContent().substring(shareDataBean.getDiscover().getContent().lastIndexOf("/")));
                if (OkDownload.getInstance().hasTask("choupai_" + shareDataBean.getDiscover().getId())
                        && file.exists()) {
                    //存在我们就获取任务继续下载
                    task = okDownload.getInstance().getTask("choupai_" + shareDataBean.getDiscover().getId()).
                            fileName(shareDataBean.getDiscover().getContent().substring(shareDataBean.getDiscover().getContent().lastIndexOf("/")));
                } else {
                    //不存在就移除任务 创建新任务重新下载
                    OkDownload.getInstance().removeTask("choupai_" + shareDataBean.getDiscover().getId());

                    GetRequest<File> request = OkGo.<File>get(shareDataBean.getDiscover().getContent()/*+"?avthumb/mp4/wmImage/aHR0cDovL3Rlc3QtMi5xaW5pdWRuLmNvbS9sb2dvLnBuZw==/wmGravity/Center"*/);
                    task = OkDownload.request("choupai_" + shareDataBean.getDiscover().getId(), request).fileName(shareDataBean.getDiscover().getContent().substring(shareDataBean.getDiscover().getContent().lastIndexOf("/"))).save();

                    task.register(new DownloadListener("choupai_" + shareDataBean.getDiscover().getId()) {
                        @Override
                        public void onStart(Progress progress) {
//                            Logger.e("下载开始");
                            showLongToast("开始下载");
                        }

                        @Override
                        public void onProgress(Progress progress) {
                            Logger.e(Integer.parseInt(progress.totalSize + "") + "-----" + Float.parseFloat(progress.currentSize + ""));

                        }

                        @Override
                        public void onError(Progress progress) {
                            Throwable throwable = progress.exception;
                            if (throwable != null) {
                                if (throwable instanceof SocketException) {
                                    showToast("网络开小差了...");
                                    throwable.printStackTrace();
                                } else if (throwable instanceof UnknownHostException) {
                                    showToast("无网络");
                                    throwable.printStackTrace();
                                } else {
                                    OkDownload.getInstance().removeTask("choupai_" + shareDataBean.getDiscover().getId());
                                    throwable.printStackTrace();
                                }
                            }
                        }

                        @Override
                        public void onFinish(File file, Progress progress) {
                            OkDownload.getInstance().removeTask("choupai_" + shareDataBean.getDiscover().getId());
                            task.unRegister(this);
                            Logger.e("下载完成");

                            String[] commandLine = null;

                            int bitRate = 500;
                            MediaMetadataRetriever retriever = new MediaMetadataRetriever();
                            retriever.setDataSource(file.getAbsolutePath());
                            String mBitRate = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_BITRATE);
                            if (mBitRate != null && !mBitRate.isEmpty()) {
                                int probeBitrate = Integer.valueOf(mBitRate);
                                bitRate = (probeBitrate / 1000 / 100) * 100;
                            }
                            //1:top left 2:top right 3:bottom left 4:bottom right
                            int location = 1;
                            int offsetXY = 5;
                            String photo = Utils.getPickerFileDirectory(context, "choupai_logo_img").getAbsolutePath() + File.separator + "choupai_water_img.png";
//                            String photoMark = "";
                            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                                photoMark = Utils.getPickerFileDirectory(context, "choupai_video_copy") + File.separator + file.getAbsolutePath().substring(file.getAbsolutePath().lastIndexOf("/"));
                            } else {
                                photoMark = Utils.getFileDirectory("choupai_video_copy").getAbsolutePath() + File.separator + file.getAbsolutePath().substring(file.getAbsolutePath().lastIndexOf("/"));
                            }
                            commandLine = FFmpegUtil.addWaterMarkImg(file.getAbsolutePath(), photo, location, bitRate, offsetXY, photoMark);

                            if (ffmpegHandler != null && commandLine != null) {
                                ffmpegHandler.executeFFmpegCmd(commandLine);
                            }
                        }

                        @Override
                        public void onRemove(Progress progress) {

                        }
                    });
                    task.save();
                    task.start();
                }
            }
        });

        dialog_share.findViewById(R.id.black_list).setVisibility(View.INVISIBLE);

        dialog_share.findViewById(R.id.report).setVisibility(View.INVISIBLE);

    }

    private int moduleInt;

    private void showShareDialog(ShareDataBean shareDataBean, int moduleInt) {
        this.moduleInt = moduleInt;
        DialogUtil.getInstance().showBottomDialog(context, R.layout.dialog_share);
        LinearLayout dialog_share = (LinearLayout) DialogUtil.getInstance().dialog_bottom_layout;
        dialog_share.findViewById(R.id.close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Utils.isDoubleClick()) {
                    return;
                }
                DialogUtil.getInstance().dialog_bottom.dismiss();
            }
        });

        dialog_share.findViewById(R.id.share_wechat).setOnClickListener(view -> {
            if (Utils.isDoubleClick()) {
                return;
            }
            DialogUtil.getInstance().dialog_bottom.dismiss();
            share_flag = "weixin";
            WXShareUtil wxShareUtil = new WXShareUtil(context);
            wxShareUtil.registerWx();
            WechatLoginUtil.getInstance().setWechatCallBack(FindVideoDetailActivity.this);
            String url = "";
            if (shareDataBean.getContent().getType() == 1) {
                url = shareDataBean.getContent().getUrls() + "?vframe/jpg/offset/1";
            } else if (shareDataBean.getContent().getType() == 2) {
                url = shareDataBean.getContent().getUrls().split("\\|")[0] + "?imageView2/2/w/100";
            } else if (shareDataBean.getContent().getType() == 3) {
                url = "";
            }
            wxShareUtil.share(shareDataBean.getUrl(),
                    shareDataBean.getContent().getTitle(),
                    "",
                    url, wxShareUtil.SHARETOFRIEND);
        });

        dialog_share.findViewById(R.id.share_wechat_friend).setOnClickListener(view -> {
            if (Utils.isDoubleClick()) {
                return;
            }
            DialogUtil.getInstance().dialog_bottom.dismiss();
            share_flag = "weixin";
            WXShareUtil wxShareUtil = new WXShareUtil(context);
            wxShareUtil.registerWx();
            WechatLoginUtil.getInstance().setWechatCallBack(FindVideoDetailActivity.this);
            String url = "";
            if (shareDataBean.getContent().getType() == 1) {
                url = shareDataBean.getContent().getUrls() + "?vframe/jpg/offset/1";
            } else if (shareDataBean.getContent().getType() == 2) {
                url = shareDataBean.getContent().getUrls().split("\\|")[0] + "?imageView2/2/w/100";
            } else if (shareDataBean.getContent().getType() == 3) {
                url = "";
            }
            wxShareUtil.share(shareDataBean.getUrl(),
                    shareDataBean.getContent().getTitle(),
                    "",
                    url, wxShareUtil.SHARETOPYQ);
        });

        dialog_share.findViewById(R.id.share_qq).setOnClickListener(view -> {
            if (Utils.isDoubleClick()) {
                return;
            }
            DialogUtil.getInstance().dialog_bottom.dismiss();
            share_flag = "qq";
            String url = "";
            if (shareDataBean.getContent().getType() == 1) {
                url = shareDataBean.getContent().getUrls() + "?vframe/jpg/offset/1";
            } else if (shareDataBean.getContent().getType() == 2) {
                url = shareDataBean.getContent().getUrls().split("\\|")[0] + "?imageView2/2/w/100";
            } else if (shareDataBean.getContent().getType() == 3) {
                url = "";
            }
            mTencent = Tencent.createInstance(Config.QQ_APP_ID, ContextUtil.getContext());
            Bundle params = new Bundle();
            params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
            params.putString(QQShare.SHARE_TO_QQ_TITLE, shareDataBean.getContent().getTitle());
            params.putString(QQShare.SHARE_TO_QQ_SUMMARY, "");
            params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, url);
            params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, shareDataBean.getUrl());
            mTencent.shareToQQ(FindVideoDetailActivity.this, params, new BaseUiListener());
            shareSucess();
        });

        dialog_share.findViewById(R.id.share_qq_space).setOnClickListener(view -> {
            if (Utils.isDoubleClick()) {
                return;
            }
            DialogUtil.getInstance().dialog_bottom.dismiss();
            share_flag = "qq";
            String url = "";
            if (shareDataBean.getContent().getType() == 1) {
                url = shareDataBean.getContent().getUrls() + "?vframe/jpg/offset/1";
            } else if (shareDataBean.getContent().getType() == 2) {
                url = shareDataBean.getContent().getUrls().split("\\|")[0] + "?imageView2/2/w/100";
            } else if (shareDataBean.getContent().getType() == 3) {
                url = "";
            }
            mTencent = Tencent.createInstance(Config.QQ_APP_ID, context);
            Bundle params = new Bundle();
            params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);
            params.putString(QzoneShare.SHARE_TO_QQ_TITLE, shareDataBean.getContent().getTitle());//选填
            params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, "");
            params.putString(QzoneShare.SHARE_TO_QQ_IMAGE_URL, url);
            params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, shareDataBean.getUrl());
            params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, new ArrayList<String>());
            mTencent.shareToQzone(FindVideoDetailActivity.this, params, new BaseUiListener());
            shareSucess();
        });

        dialog_share.findViewById(R.id.share_weibo).setOnClickListener(view -> {
            if (Utils.isDoubleClick()) {
                return;
            }
            DialogUtil.getInstance().dialog_bottom.dismiss();
            share_flag = "weibo";
            WbSdk.install(ContextUtil.getContext(), new AuthInfo(ContextUtil.getContext(), Config.SINA_APP_KEY, Config.REDIRECT_URL, ""));
            shareHandler = new WbShareHandler(FindVideoDetailActivity.this);
            shareHandler.registerApp();
            WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
            weiboMessage.textObject = getTextObj(shareDataBean.getUrl(), shareDataBean.getContent().getTitle());
            shareHandler.shareMessage(weiboMessage, false);
            shareSucess();
        });

        dialog_share.findViewById(R.id.copy_link).setOnClickListener(view -> {
            if (Utils.isDoubleClick()) {
                return;
            }
            DialogUtil.getInstance().dialog_bottom.dismiss();
            ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
            // 创建一个剪贴数据集，包含一个普通文本数据条目（需要复制的数据）
            ClipData clipData = ClipData.newPlainText(null, shareDataBean.getUrl());
            // 把数据集设置（复制）到剪贴板
            clipboard.setPrimaryClip(clipData);
            showToast("链接已复制");
        });

        dialog_share.findViewById(R.id.copy_text).setOnClickListener(view -> {
            if (Utils.isDoubleClick()) {
                return;
            }
            DialogUtil.getInstance().dialog_bottom.dismiss();
            ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
            // 创建一个剪贴数据集，包含一个普通文本数据条目（需要复制的数据）
            ClipData clipData = ClipData.newPlainText(null, shareDataBean.getContent().getTitle());
            // 把数据集设置（复制）到剪贴板
            clipboard.setPrimaryClip(clipData);
            showToast("文字已复制");
        });

        ImageView copy_text_iv = dialog_share.findViewById(R.id.black_list_iv);
        copy_text_iv.setImageResource(R.mipmap.download_video);
        TextView copy_text_tv = dialog_share.findViewById(R.id.black_list_tv);
        copy_text_tv.setText("下载视频");

        dialog_share.findViewById(R.id.black_list).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogUtil.getInstance().dialog_bottom.dismiss();
                File file = new File(Utils.getPickerFileDirectory(context, "choupai_video"),
                        shareDataBean.getContent().getUrls().substring(shareDataBean.getContent().getUrls().lastIndexOf("/")));
                if (OkDownload.getInstance().hasTask("choupai_" + shareDataBean.getContent().getId())
                        && file.exists()) {
                    //存在我们就获取任务继续下载
                    task = okDownload.getInstance().getTask("choupai_" + shareDataBean.getContent().getId()).
                            fileName(shareDataBean.getContent().getUrls().substring(shareDataBean.getContent().getUrls().lastIndexOf("/")));
                } else {
                    //不存在就移除任务 创建新任务重新下载
                    OkDownload.getInstance().removeTask("choupai_" + shareDataBean.getContent().getId());

                    GetRequest<File> request = OkGo.<File>get(shareDataBean.getContent().getUrls()/*+"?avthumb/mp4/wmImage/aHR0cDovL3Rlc3QtMi5xaW5pdWRuLmNvbS9sb2dvLnBuZw==/wmGravity/Center"*/);
                    task = OkDownload.request("choupai_" + shareDataBean.getContent().getId(), request).fileName(shareDataBean.getContent().getUrls().substring(shareDataBean.getContent().getUrls().lastIndexOf("/"))).save();

                    task.register(new DownloadListener("choupai_" + shareDataBean.getContent().getId()) {
                        @Override
                        public void onStart(Progress progress) {
//                            Logger.e("下载开始");
                            showLongToast("开始下载");
                        }

                        @Override
                        public void onProgress(Progress progress) {
                            Logger.e(Integer.parseInt(progress.totalSize + "") + "-----" + Float.parseFloat(progress.currentSize + ""));

                        }

                        @Override
                        public void onError(Progress progress) {
                            Throwable throwable = progress.exception;
                            if (throwable != null) {
                                if (throwable instanceof SocketException) {
                                    showToast("网络开小差了...");
                                    throwable.printStackTrace();
                                } else if (throwable instanceof UnknownHostException) {
                                    showToast("无网络");
                                    throwable.printStackTrace();
                                } else {
                                    OkDownload.getInstance().removeTask("choupai_" + shareDataBean.getContent().getId());
                                    throwable.printStackTrace();
                                }
                            }
                        }

                        @Override
                        public void onFinish(File file, Progress progress) {
                            OkDownload.getInstance().removeTask("choupai_" + shareDataBean.getContent().getId());
                            task.unRegister(this);
                            Logger.e("下载完成");

                            String[] commandLine = null;

                            int bitRate = 500;
                            MediaMetadataRetriever retriever = new MediaMetadataRetriever();
                            retriever.setDataSource(file.getAbsolutePath());
                            String mBitRate = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_BITRATE);
                            if (mBitRate != null && !mBitRate.isEmpty()) {
                                int probeBitrate = Integer.valueOf(mBitRate);
                                bitRate = (probeBitrate / 1000 / 100) * 100;
                            }
                            //1:top left 2:top right 3:bottom left 4:bottom right
                            int location = 1;
                            int offsetXY = 5;
                            String photo = Utils.getPickerFileDirectory(context, "choupai_logo_img").getAbsolutePath() + File.separator + "choupai_water_img.png";
//                            String photoMark = "";
                            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                                photoMark = Utils.getPickerFileDirectory(context, "choupai_video_copy") + File.separator + file.getAbsolutePath().substring(file.getAbsolutePath().lastIndexOf("/"));
                            } else {
                                photoMark = Utils.getFileDirectory("choupai_video_copy").getAbsolutePath() + File.separator + file.getAbsolutePath().substring(file.getAbsolutePath().lastIndexOf("/"));
                            }
                            commandLine = FFmpegUtil.addWaterMarkImg(file.getAbsolutePath(), photo, location, bitRate, offsetXY, photoMark);

                            if (ffmpegHandler != null && commandLine != null) {
                                ffmpegHandler.executeFFmpegCmd(commandLine);
                            }
                        }

                        @Override
                        public void onRemove(Progress progress) {

                        }
                    });
                    task.save();
                    task.start();
                }
            }
        });
        dialog_share.findViewById(R.id.report).setVisibility(View.INVISIBLE);

    }

    @Override
    public void onWbShareSuccess() {
//        showToast("分享成功");
//        shareSucess();
    }

    @Override
    public void onWbShareCancel() {
//        showImageToas("分享取消");
    }

    @Override
    public void onWbShareFail() {
//        showImageToas("分享失败");
    }

    @Override
    public void callBack(BaseResp baseResp) {
        switch (baseResp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                showToast("分享成功");
                shareSucess();
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                showImageToas("分享取消");
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                showImageToas("分享被拒绝");
                break;
            default:
                showImageToas("分享返回");
                break;
        }
    }

    private class BaseUiListener implements IUiListener {

        @Override
        public void onComplete(Object o) {
//            showToast("分享成功");
//            shareSucess();
        }

        @Override
        public void onError(UiError uiError) {
//            showImageToas("分享失败");
        }

        @Override
        public void onCancel() {
//            showImageToas("分享取消");
        }

    }

    private void shareSucess() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("contentId", listBeans.get(sharePosition).getContentId());
            jsonObject.put("module", moduleInt);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        finalOkGo.requestHead(RequestType.POSTJSONHEAD, Url.SHARE_SUCCESS, null, jsonObject.toString(), new Callback<SendCodeBean>() {
            @Override
            public void onSuccess(SendCodeBean sendCodeBean) {
                if (sendCodeBean.getCode() == Contacts.SUCCESS) {

                } else {
                    if (sendCodeBean.getCode() == Contacts.TOKEN_EMPTY) {
                    } else {
                        showImageToas(sendCodeBean.getMsg());
                    }
                }
            }
        });
    }

    private String share_flag = "";

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (share_flag.equals("weibo")) {
            shareHandler.doResultIntent(data, this);
        } else if (share_flag.equals("qq")) {
            if (mTencent != null) {
                mTencent.onActivityResult(requestCode, resultCode, data);
            }
        }
    }


    private TextObject getTextObj(String url, String title) {
        TextObject textObject = new TextObject();
        textObject.text = title + "\n" + url;
        textObject.title = title;
        textObject.actionUrl = url;
        return textObject;
    }

    @Override
    public void onHeadClick(int position) {
        if (listBeans.get(position).getAnonymity() == 1) {
            showImageToas("匿名用户无法查看主页");
        } else {
            Bundle bundle = new Bundle();
            bundle.putString("userId", listBeans.get(position).getUserId() + "");
            bundle.putString("userName", listBeans.get(position).getNickName());
            startActivity(FindOtherInfoActivity.class, bundle);
        }
    }

    @Override
    public void onBack() {
//        AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
//        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, audioManager.getStreamVolume(AudioManager.STREAM_MUSIC), AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
        EventBus.getDefault().unregister(this);
        if (listBeans != null) {
            for (int i = 0; i < listBeans.size(); i++) {
                VideoView videoView = VideoDetailHashMap.getIntance().get(listBeans.get(i).getContentId());
                if (i != 0) {
                    if (videoView != null) {
                        removePlayerFormParent(videoView);
                        //移除Controller
                        videoView.setVideoController(null);
                    }
                }
            }
        }
        if (VideoDetailHashMap.getIntance() != null) {
            VideoDetailHashMap.getIntance().clear();
        }
        mPreloadManager.removeAllPreloadTask();
        if ("mineVideo".equals(flag)) {
//            EventBus.getDefault().post("replay");
        } else if ("mineAll".equals(flag)) {
            EventBus.getDefault().post("replay_mine");
        } else if ("praise".equals(flag)) {
            EventBus.getDefault().post("replay_search");
        } else if ("search".equals(flag)) {
            EventBus.getDefault().post("replay_search");
        } else if ("recommend".equals(flag)) {
            EventBus.getDefault().post("replay");
        } else {
            EventBus.getDefault().post("replay");
        }
        finishActivity();
    }

    private long formattingtime;
    private long TimeCha;

    private void timecha(String startime, TextView textView) {
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dataformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long currenttime = calendar.getTimeInMillis();//获取系统当先时间的毫秒值
        try {//如果你的初始时间是格式化过的,则需要先转化成毫秒值
            formattingtime = dataformat.parse(startime).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
//这里需要注意,因为获取的时间因为时差的缘故已经自动加上了8小时的时间,所以这里需要减去.如果不减去,就算是你刚刚发布的动态也会显示是8小时之前
        TimeCha = ((currenttime - formattingtime) / 1000) /*- (8 * 60 * 60)*/;//将毫秒值转化成分钟数
//        Logger.e(TimeCha+"");
        if (TimeCha < 60) {
            textView.setText("刚刚");
        } else if (TimeCha >= 60 && TimeCha < 3600) {
            textView.setText(TimeCha / 60 + "分钟前");
        } else if (TimeCha >= 3600 && TimeCha < 3600 * 24) {
            textView.setText(TimeCha / 3600 + "小时前");
        } else if (TimeCha >= 3600 * 1 * 24 && TimeCha < 3600 * 31 * 24) {
            textView.setText(TimeCha / 3600 / 24 + "天前");
        } else if (TimeCha >= 3600 * 31 * 24 * 1 && TimeCha < 3600 * 31 * 24 * 12) {
            textView.setText(TimeCha / 3600 / 24 / 30 + "个月前");
        } else {
            textView.setText(TimeCha / 3600 / 24 / 30 / 12 + "年前");
        }
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        requestComment(mPlayingPosition);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        pageNum = 1;
        requestComment(mPlayingPosition);

    }
}
